<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>RabbitMQ工作模式 | 樱桃小窝</title><meta name="keywords" content="RabbitMQ"><meta name="author" content="樱桃先生"><meta name="copyright" content="樱桃先生"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="RabbitMQ工作模式官网对应模式介绍：https:&#x2F;&#x2F;www.rabbitmq.com&#x2F;getstarted.html  1. Work queues工作队列模式1.1 模式说明 Work Queues与入门程序的简单模式相比，多了一个或一些消费端，多个消费端共同消费同一个队列中的消息。 应用场景：对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度。 1.2 代码Work Queu">
<meta property="og:type" content="article">
<meta property="og:title" content="RabbitMQ工作模式">
<meta property="og:url" content="http://example.com/posts/a7bd23d6/index.html">
<meta property="og:site_name" content="樱桃小窝">
<meta property="og:description" content="RabbitMQ工作模式官网对应模式介绍：https:&#x2F;&#x2F;www.rabbitmq.com&#x2F;getstarted.html  1. Work queues工作队列模式1.1 模式说明 Work Queues与入门程序的简单模式相比，多了一个或一些消费端，多个消费端共同消费同一个队列中的消息。 应用场景：对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度。 1.2 代码Work Queu">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg">
<meta property="article:published_time" content="2021-03-15T16:51:00.000Z">
<meta property="article:modified_time" content="2021-03-15T16:51:00.000Z">
<meta property="article:author" content="樱桃先生">
<meta property="article:tag" content="RabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/posts/a7bd23d6/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'RabbitMQ工作模式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-16 00:51:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/20/hk9Zvq4YRsIcnrw.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">78</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">65</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间线</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">樱桃小窝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间线</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/gallery/"><i class="fa-fw fas fa-camera"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fas fa-comment-dots"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">RabbitMQ工作模式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-03-15T16:51:00.000Z" title="发表于 2021-03-16 00:51:00">2021-03-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-03-15T16:51:00.000Z" title="更新于 2021-03-16 00:51:00">2021-03-16</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF/RabbitMQ/">RabbitMQ</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="RabbitMQ工作模式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="RabbitMQ工作模式"><a href="#RabbitMQ工作模式" class="headerlink" title="RabbitMQ工作模式"></a>RabbitMQ工作模式</h1><p>官网对应模式介绍：<a target="_blank" rel="noopener" href="https://www.rabbitmq.com/getstarted.html">https://www.rabbitmq.com/getstarted.html</a></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1555988678324-1607960269112.png" alt="1555988678324"></p>
<h2 id="1-Work-queues工作队列模式"><a href="#1-Work-queues工作队列模式" class="headerlink" title="1. Work queues工作队列模式"></a>1. Work queues工作队列模式</h2><h3 id="1-1-模式说明"><a href="#1-1-模式说明" class="headerlink" title="1.1 模式说明"></a>1.1 模式说明</h3><p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556009144848.png" alt="1556009144848"></p>
<p><code>Work Queues</code>与入门程序的<code>简单模式</code>相比，多了一个或一些消费端，多个消费端共同消费同一个队列中的消息。</p>
<p><code>应用场景</code>：对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度。</p>
<h3 id="1-2-代码"><a href="#1-2-代码" class="headerlink" title="1.2 代码"></a>1.2 代码</h3><p><code>Work Queues</code>与入门程序的<code>简单模式</code>的代码是几乎一样的；可以完全复制，并复制多一个消费者进行多个消费者同时消费消息的测试。</p>
<h4 id="生产者"><a href="#生产者" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.producer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer_WorkQueues</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5. 创建队列Queue</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. durable:是否持久化，当mq重启之后，还在</span></span><br><span class="line"><span class="comment">            3. exclusive：</span></span><br><span class="line"><span class="comment">                * 是否独占。只能有一个消费者监听这队列</span></span><br><span class="line"><span class="comment">                * 当Connection关闭时，是否删除队列</span></span><br><span class="line"><span class="comment">                *</span></span><br><span class="line"><span class="comment">            4. autoDelete:是否自动删除。当没有Consumer时，自动删除掉</span></span><br><span class="line"><span class="comment">            5. arguments：参数。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//如果没有一个名字叫hello_world的队列，则会创建该队列，如果有则不会创建</span></span><br><span class="line">        channel.queueDeclare(<span class="string">&quot;work_queues&quot;</span>, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. exchange：交换机名称。简单模式下交换机会使用默认的 &quot;&quot;</span></span><br><span class="line"><span class="comment">            2. routingKey：路由名称</span></span><br><span class="line"><span class="comment">            3. props：配置信息</span></span><br><span class="line"><span class="comment">            4. body：发送消息数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;= <span class="number">10</span>; i++) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">body</span> <span class="operator">=</span> i + <span class="string">&quot;hello rabbitmq~~~&quot;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//6. 发送消息</span></span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, <span class="string">&quot;work_queues&quot;</span>, <span class="literal">null</span>, body.getBytes());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//7.释放资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214233115280.png" alt="image-20201214233115280"></p>
<h4 id="消费者1"><a href="#消费者1" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_WorkQueues1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">        <span class="comment">//5. 创建队列Queue</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. durable:是否持久化，当mq重启之后，还在</span></span><br><span class="line"><span class="comment">            3. exclusive：</span></span><br><span class="line"><span class="comment">                * 是否独占。只能有一个消费者监听这队列</span></span><br><span class="line"><span class="comment">                * 当Connection关闭时，是否删除队列</span></span><br><span class="line"><span class="comment">                *</span></span><br><span class="line"><span class="comment">            4. autoDelete:是否自动删除。当没有Consumer时，自动删除掉</span></span><br><span class="line"><span class="comment">            5. arguments：参数。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//如果没有一个名字叫hello_world的队列，则会创建该队列，如果有则不会创建</span></span><br><span class="line">        channel.queueDeclare(<span class="string">&quot;work_queues&quot;</span>,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(<span class="string">&quot;work_queues&quot;</span>,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者2"><a href="#消费者2" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_WorkQueues2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">        <span class="comment">//5. 创建队列Queue</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. durable:是否持久化，当mq重启之后，还在</span></span><br><span class="line"><span class="comment">            3. exclusive：</span></span><br><span class="line"><span class="comment">                * 是否独占。只能有一个消费者监听这队列</span></span><br><span class="line"><span class="comment">                * 当Connection关闭时，是否删除队列</span></span><br><span class="line"><span class="comment">                *</span></span><br><span class="line"><span class="comment">            4. autoDelete:是否自动删除。当没有Consumer时，自动删除掉</span></span><br><span class="line"><span class="comment">            5. arguments：参数。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//如果没有一个名字叫hello_world的队列，则会创建该队列，如果有则不会创建</span></span><br><span class="line">        channel.queueDeclare(<span class="string">&quot;work_queues&quot;</span>, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel) &#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(<span class="string">&quot;work_queues&quot;</span>, <span class="literal">true</span>, consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="1-3-测试"><a href="#1-3-测试" class="headerlink" title="1.3 测试"></a>1.3 测试</h3><p>启动两个消费者，然后再启动生产者发送消息；到IDEA的两个消费者对应的控制台查看是否竞争性的接收到消息。</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214233458985.png" alt="image-20201214233458985"></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214233412557.png" alt="image-20201214233412557"></p>
<h3 id="1-4-小结"><a href="#1-4-小结" class="headerlink" title="1.4 小结"></a>1.4 小结</h3><p>在一个队列中如果有多个消费者，那么消费者之间对于同一个消息的关系是<code>竞争</code>的关系。</p>
<h2 id="2-订阅模式类型"><a href="#2-订阅模式类型" class="headerlink" title="2. 订阅模式类型"></a>2. 订阅模式类型</h2><p>订阅模式示例图：</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556014499573.png" alt="1556014499573"></p>
<p>前面2个案例中，只有3个角色：</p>
<ul>
<li>P：生产者，也就是要发送消息的程序</li>
<li>C：消费者：消息的接受者，会一直等待消息到来。</li>
<li>queue：消息队列，图中红色部分</li>
</ul>
<p>而在订阅模型中，多了一个exchange角色，而且过程略有变化：</p>
<ul>
<li>P：生产者，也就是要发送消息的程序，但是不再发送到队列中，而是发给X（交换机）</li>
<li>C：消费者，消息的接受者，会一直等待消息到来。</li>
<li>Queue：消息队列，接收消息、缓存消息。</li>
<li>Exchange：交换机，图中的X。一方面，接收生产者发送的消息。另一方面，知道如何处理消息，例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作，取决于Exchange的类型。Exchange有常见以下3种类型：<ul>
<li>Fanout：广播，将消息交给所有绑定到交换机的队列</li>
<li>Direct：定向，把消息交给符合指定routing key 的队列</li>
<li>Topic：通配符，把消息交给符合routing pattern（路由模式） 的队列</li>
</ul>
</li>
</ul>
<p><code>Exchange（交换机）只负责转发消息，不具备存储消息的能力</code>，因此如果没有任何队列与Exchange绑定，或者没有符合路由规则的队列，那么消息会丢失！</p>
<h2 id="3-Publish-Subscribe发布与订阅模式"><a href="#3-Publish-Subscribe发布与订阅模式" class="headerlink" title="3. Publish/Subscribe发布与订阅模式"></a>3. Publish/Subscribe发布与订阅模式</h2><h3 id="3-1-模式说明"><a href="#3-1-模式说明" class="headerlink" title="3.1 模式说明"></a>3.1 模式说明</h3><p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556010329032.png" alt="1556010329032"></p>
<p>发布订阅模式：<br>1、每个消费者监听自己的队列。<br>2、生产者将消息发给broker，由交换机将消息转发到绑定此交换机的每个队列，每个绑定交换机的队列都将接收<br>到消息。</p>
<h3 id="3-2-代码"><a href="#3-2-代码" class="headerlink" title="3.2. 代码"></a>3.2. 代码</h3><h4 id="生产者-1"><a href="#生产者-1" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.producer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer_PubSub</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">       <span class="comment">/*</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">       exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">       参数：</span></span><br><span class="line"><span class="comment">        1. exchange:交换机名称</span></span><br><span class="line"><span class="comment">        2. type:交换机类型</span></span><br><span class="line"><span class="comment">            DIRECT(&quot;direct&quot;),：定向</span></span><br><span class="line"><span class="comment">            FANOUT(&quot;fanout&quot;),：扇形（广播），发送消息到每一个与之绑定队列。</span></span><br><span class="line"><span class="comment">            TOPIC(&quot;topic&quot;),通配符的方式</span></span><br><span class="line"><span class="comment">            HEADERS(&quot;headers&quot;);参数匹配</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">        3. durable:是否持久化</span></span><br><span class="line"><span class="comment">        4. autoDelete:自动删除</span></span><br><span class="line"><span class="comment">        5. internal：内部使用。 一般false</span></span><br><span class="line"><span class="comment">        6. arguments：参数</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">exchangeName</span> <span class="operator">=</span> <span class="string">&quot;test_fanout&quot;</span>;</span><br><span class="line">        <span class="comment">//5. 创建交换机</span></span><br><span class="line">        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//6. 创建队列</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue2&quot;</span>;</span><br><span class="line">        channel.queueDeclare(queue1Name, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        channel.queueDeclare(queue2Name, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//7. 绑定队列和交换机</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueBind(String queue, String exchange, String routingKey)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. exchange：交换机名称</span></span><br><span class="line"><span class="comment">            3. routingKey：路由键，绑定规则</span></span><br><span class="line"><span class="comment">                如果交换机的类型为fanout ，routingKey设置为&quot;&quot;</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        channel.queueBind(queue1Name, exchangeName, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        channel.queueBind(queue2Name, exchangeName, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">body</span> <span class="operator">=</span> <span class="string">&quot;日志信息：张三调用了findAll方法...日志级别：info...&quot;</span>;</span><br><span class="line">        <span class="comment">//8. 发送消息</span></span><br><span class="line">        channel.basicPublish(exchangeName, <span class="string">&quot;&quot;</span>, <span class="literal">null</span>, body.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//9. 释放资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者1-1"><a href="#消费者1-1" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_PubSub1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息打印到控制台.....&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue1Name,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者2-1"><a href="#消费者2-1" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_PubSub2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_fanout_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息保存数据库.....&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue2Name,<span class="literal">true</span>,consumer);</span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-3-测试"><a href="#3-3-测试" class="headerlink" title="3.3 测试"></a>3.3 测试</h3><p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214235015805.png" alt="image-20201214235015805"></p>
<p>启动所有消费者，然后使用生产者发送消息；在每个消费者对应的控制台可以查看到生产者发送的所有消息；到达<code>广播</code>的效果。</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214234959997.png" alt="image-20201214234959997"></p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>fanout_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214234927452.png" alt="image-20201214234927452"></p>
<h3 id="3-4-小结"><a href="#3-4-小结" class="headerlink" title="3.4 小结"></a>3.4 小结</h3><p>交换机需要与队列进行绑定，绑定之后；一个消息可以被多个消费者都收到。</p>
<p><code>发布订阅模式与工作队列模式的区别</code></p>
<p>1、工作队列模式不用定义交换机，而发布/订阅模式需要定义交换机。 </p>
<p>2、发布/订阅模式的生产方是面向交换机发送消息，工作队列模式的生产方是面向队列发送消息(底层使用默认交换机)。</p>
<p>3、发布/订阅模式需要设置队列和交换机的绑定，工作队列模式不需要设置，实际上工作队列模式会将队列绑 定到默认的交换机 。</p>
<h2 id="4-Routing路由模式"><a href="#4-Routing路由模式" class="headerlink" title="4. Routing路由模式"></a>4. Routing路由模式</h2><h3 id="4-1-模式说明"><a href="#4-1-模式说明" class="headerlink" title="4.1 模式说明"></a>4.1 模式说明</h3><p>路由模式特点：</p>
<ul>
<li>队列与交换机的绑定，不能是任意绑定了，而是要指定一个<code>RoutingKey</code>（路由key）</li>
<li>消息的发送方在 向Exchange发送消息时，也必须指定消息的 <code>RoutingKey</code>。</li>
<li>Exchange不再把消息交给每一个绑定的队列，而是根据消息的<code>Routing Key</code>进行判断，只有队列的<code>Routingkey</code>与消息的 <code>Routing key</code>完全一致，才会接收到消息</li>
</ul>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556029284397.png" alt="1556029284397"></p>
<p>图解：</p>
<ul>
<li>P：生产者，向Exchange发送消息，发送消息时，会指定一个routing key。</li>
<li>X：Exchange（交换机），接收生产者的消息，然后把消息递交给 与routing key完全匹配的队列</li>
<li>C1：消费者，其所在队列指定了需要routing key 为 error 的消息</li>
<li>C2：消费者，其所在队列指定了需要routing key 为 info、error、warning 的消息</li>
</ul>
<h3 id="4-2-代码"><a href="#4-2-代码" class="headerlink" title="4.2 代码"></a>4.2 代码</h3><p>在编码上与 <code>Publish/Subscribe发布与订阅模式</code> 的区别是交换机的类型为：Direct，还有队列绑定交换机的时候需要指定routing key。</p>
<h4 id="生产者-2"><a href="#生产者-2" class="headerlink" title="生产者"></a>生产者</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.producer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer_Routing</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">       <span class="comment">/*</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">       exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">       参数：</span></span><br><span class="line"><span class="comment">        1. exchange:交换机名称</span></span><br><span class="line"><span class="comment">        2. type:交换机类型</span></span><br><span class="line"><span class="comment">            DIRECT(&quot;direct&quot;),：定向</span></span><br><span class="line"><span class="comment">            FANOUT(&quot;fanout&quot;),：扇形（广播），发送消息到每一个与之绑定队列。</span></span><br><span class="line"><span class="comment">            TOPIC(&quot;topic&quot;),通配符的方式</span></span><br><span class="line"><span class="comment">            HEADERS(&quot;headers&quot;);参数匹配</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">        3. durable:是否持久化</span></span><br><span class="line"><span class="comment">        4. autoDelete:自动删除</span></span><br><span class="line"><span class="comment">        5. internal：内部使用。 一般false</span></span><br><span class="line"><span class="comment">        6. arguments：参数</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line"></span><br><span class="line">       <span class="type">String</span> <span class="variable">exchangeName</span> <span class="operator">=</span> <span class="string">&quot;test_direct&quot;</span>;</span><br><span class="line">        <span class="comment">//5. 创建交换机</span></span><br><span class="line">        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//6. 创建队列</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line">        channel.queueDeclare(queue1Name,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line">        channel.queueDeclare(queue2Name,<span class="literal">true</span>,<span class="literal">false</span>,<span class="literal">false</span>,<span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//7. 绑定队列和交换机</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueBind(String queue, String exchange, String routingKey)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. exchange：交换机名称</span></span><br><span class="line"><span class="comment">            3. routingKey：路由键，绑定规则</span></span><br><span class="line"><span class="comment">                如果交换机的类型为fanout ，routingKey设置为&quot;&quot;</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//队列1绑定 error</span></span><br><span class="line">        channel.queueBind(queue1Name,exchangeName,<span class="string">&quot;error&quot;</span>);</span><br><span class="line">        <span class="comment">//队列2绑定 info  error  warning</span></span><br><span class="line">        channel.queueBind(queue2Name,exchangeName,<span class="string">&quot;info&quot;</span>);</span><br><span class="line">        channel.queueBind(queue2Name,exchangeName,<span class="string">&quot;error&quot;</span>);</span><br><span class="line">        channel.queueBind(queue2Name,exchangeName,<span class="string">&quot;warning&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">body</span> <span class="operator">=</span> <span class="string">&quot;日志信息：张三调用了delete方法...出错误了。。。日志级别：error...&quot;</span>;</span><br><span class="line">        <span class="comment">//8. 发送消息</span></span><br><span class="line">        channel.basicPublish(exchangeName,<span class="string">&quot;warning&quot;</span>,<span class="literal">null</span>,body.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//9. 释放资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214235530308.png" alt="image-20201214235530308"></p>
<h4 id="消费者1-2"><a href="#消费者1-2" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_Routing1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息打印到控制台.....&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue1Name,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者2-2"><a href="#消费者2-2" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_Routing2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_direct_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息存储到数据库.....&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue2Name,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="4-3-测试"><a href="#4-3-测试" class="headerlink" title="4.3 测试"></a>4.3 测试</h3><p>启动所有消费者，然后使用生产者发送消息；在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息；到达<code>按照需要接收</code>的效果。</p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>direct_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201214235922773.png" alt="image-20201214235922773"></p>
<h3 id="4-4-小结"><a href="#4-4-小结" class="headerlink" title="4.4 小结"></a>4.4 小结</h3><p>Routing模式要求队列在绑定交换机时要指定routing key，消息会转发到符合routing key的队列。</p>
<h2 id="5-Topics通配符模式"><a href="#5-Topics通配符模式" class="headerlink" title="5. Topics通配符模式"></a>5. Topics通配符模式</h2><h3 id="5-1-模式说明"><a href="#5-1-模式说明" class="headerlink" title="5.1. 模式说明"></a>5.1. 模式说明</h3><p><code>Topic</code>类型与<code>Direct</code>相比，都是可以根据<code>RoutingKey</code>把消息路由到不同的队列。只不过<code>Topic</code>类型<code>Exchange</code>可以让队列在绑定<code>Routing key</code> 的时候<code>使用通配符</code>！</p>
<p><code>Routingkey</code> 一般都是有一个或多个单词组成，多个单词之间以”.”分割，例如： <code>item.insert</code></p>
<p> 通配符规则：</p>
<p><code>#</code>：匹配一个或多个词</p>
<p><code>*</code>：匹配不多不少恰好1个词</p>
<p>举例：</p>
<p><code>item.#</code>：能够匹配<code>item.insert.abc</code> 或者 <code>item.insert</code></p>
<p><code>item.*</code>：只能匹配<code>item.insert</code></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556031362048.png" alt="1556031362048"></p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/1556031519931.png" alt="1556031519931"></p>
<p>图解：</p>
<ul>
<li>红色Queue：绑定的是<code>usa.#</code> ，因此凡是以 <code>usa.</code>开头的<code>routing key</code> 都会被匹配到</li>
<li>黄色Queue：绑定的是<code>#.news</code> ，因此凡是以 <code>.news</code>结尾的 <code>routing key</code> 都会被匹配</li>
</ul>
<h3 id="5-2-代码"><a href="#5-2-代码" class="headerlink" title="5.2. 代码"></a>5.2. 代码</h3><h4 id="生产者-3"><a href="#生产者-3" class="headerlink" title="生产者"></a>生产者</h4><p>所有error级别的日志存入数据库，所有order系统的日志存入数据库</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.producer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.BuiltinExchangeType;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Channel;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.Connection;</span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.ConnectionFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送消息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Producer_Topics</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line">       <span class="comment">/*</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">       exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map&lt;String, Object&gt; arguments)</span></span><br><span class="line"><span class="comment">       参数：</span></span><br><span class="line"><span class="comment">        1. exchange:交换机名称</span></span><br><span class="line"><span class="comment">        2. type:交换机类型</span></span><br><span class="line"><span class="comment">            DIRECT(&quot;direct&quot;),：定向</span></span><br><span class="line"><span class="comment">            FANOUT(&quot;fanout&quot;),：扇形（广播），发送消息到每一个与之绑定队列。</span></span><br><span class="line"><span class="comment">            TOPIC(&quot;topic&quot;),通配符的方式</span></span><br><span class="line"><span class="comment">            HEADERS(&quot;headers&quot;);参数匹配</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">        3. durable:是否持久化</span></span><br><span class="line"><span class="comment">        4. autoDelete:自动删除</span></span><br><span class="line"><span class="comment">        5. internal：内部使用。 一般false</span></span><br><span class="line"><span class="comment">        6. arguments：参数</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">exchangeName</span> <span class="operator">=</span> <span class="string">&quot;test_topic&quot;</span>;</span><br><span class="line">        <span class="comment">//5. 创建交换机</span></span><br><span class="line">        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//6. 创建队列</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue2&quot;</span>;</span><br><span class="line">        channel.queueDeclare(queue1Name, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        channel.queueDeclare(queue2Name, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">null</span>);</span><br><span class="line">        <span class="comment">//7. 绑定队列和交换机</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        queueBind(String queue, String exchange, String routingKey)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. exchange：交换机名称</span></span><br><span class="line"><span class="comment">            3. routingKey：路由键，绑定规则</span></span><br><span class="line"><span class="comment">                如果交换机的类型为fanout ，routingKey设置为&quot;&quot;</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// routing key  系统的名称.日志的级别。</span></span><br><span class="line">        <span class="comment">//=需求： 所有error级别的日志存入数据库，所有order系统的日志存入数据库</span></span><br><span class="line">        channel.queueBind(queue1Name, exchangeName, <span class="string">&quot;#.error&quot;</span>);</span><br><span class="line">        channel.queueBind(queue1Name, exchangeName, <span class="string">&quot;order.*&quot;</span>);</span><br><span class="line">        channel.queueBind(queue2Name, exchangeName, <span class="string">&quot;*.*&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">body</span> <span class="operator">=</span> <span class="string">&quot;日志信息：张三调用了findAll方法...日志级别：info...&quot;</span>;</span><br><span class="line">        <span class="comment">//8. 发送消息</span></span><br><span class="line">        channel.basicPublish(exchangeName, <span class="string">&quot;goods.error&quot;</span>, <span class="literal">null</span>, body.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//9. 释放资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者1-3"><a href="#消费者1-3" class="headerlink" title="消费者1"></a>消费者1</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_Topic1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息存入数据库.......&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue1Name,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="消费者2-3"><a href="#消费者2-3" class="headerlink" title="消费者2"></a>消费者2</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.itheima.consumer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.rabbitmq.client.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeoutException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Consumer_Topic2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建连接工厂</span></span><br><span class="line">        <span class="type">ConnectionFactory</span> <span class="variable">factory</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ConnectionFactory</span>();</span><br><span class="line">        <span class="comment">//2. 设置参数</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;106.15.72.229&quot;</span>);<span class="comment">//ip  默认值 localhost</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>); <span class="comment">//端口  默认值 5672</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/itcast&quot;</span>);<span class="comment">//虚拟机 默认值/</span></span><br><span class="line">        factory.setUsername(<span class="string">&quot;heima&quot;</span>);<span class="comment">//用户名 默认 guest</span></span><br><span class="line">        factory.setPassword(<span class="string">&quot;heima&quot;</span>);<span class="comment">//密码 默认值 guest</span></span><br><span class="line">        <span class="comment">//3. 创建连接 Connection</span></span><br><span class="line">        <span class="type">Connection</span> <span class="variable">connection</span> <span class="operator">=</span> factory.newConnection();</span><br><span class="line">        <span class="comment">//4. 创建Channel</span></span><br><span class="line">        <span class="type">Channel</span> <span class="variable">channel</span> <span class="operator">=</span> connection.createChannel();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">queue1Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue1&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">queue2Name</span> <span class="operator">=</span> <span class="string">&quot;test_topic_queue2&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        basicConsume(String queue, boolean autoAck, Consumer callback)</span></span><br><span class="line"><span class="comment">        参数：</span></span><br><span class="line"><span class="comment">            1. queue：队列名称</span></span><br><span class="line"><span class="comment">            2. autoAck：是否自动确认</span></span><br><span class="line"><span class="comment">            3. callback：回调对象</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">// 接收消息</span></span><br><span class="line">        <span class="type">Consumer</span> <span class="variable">consumer</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">DefaultConsumer</span>(channel)&#123;</span><br><span class="line">            <span class="comment">/*</span></span><br><span class="line"><span class="comment">                回调方法，当收到消息后，会自动执行该方法</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">                1. consumerTag：标识</span></span><br><span class="line"><span class="comment">                2. envelope：获取一些信息，交换机，路由key...</span></span><br><span class="line"><span class="comment">                3. properties:配置信息</span></span><br><span class="line"><span class="comment">                4. body：数据</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, <span class="type">byte</span>[] body)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">              <span class="comment">/*  System.out.println(&quot;consumerTag：&quot;+consumerTag);</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;Exchange：&quot;+envelope.getExchange());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;RoutingKey：&quot;+envelope.getRoutingKey());</span></span><br><span class="line"><span class="comment">                System.out.println(&quot;properties：&quot;+properties);*/</span></span><br><span class="line">                System.out.println(<span class="string">&quot;body：&quot;</span>+<span class="keyword">new</span> <span class="title class_">String</span>(body));</span><br><span class="line">                System.out.println(<span class="string">&quot;将日志信息打印控制台.......&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        channel.basicConsume(queue2Name,<span class="literal">true</span>,consumer);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭资源？不要</span></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-3-测试"><a href="#5-3-测试" class="headerlink" title="5.3 测试"></a>5.3 测试</h3><p>启动所有消费者，然后使用生产者发送消息；在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息；到达<code>按照需要接收</code>的效果；并且这些routing key可以使用通配符。</p>
<p>在执行完测试代码后，其实到RabbitMQ的管理后台找到<code>Exchanges</code>选项卡，点击 <code>topic_exchange</code> 的交换机，可以查看到如下的绑定：</p>
<p><img src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/image-20201215000614183.png" alt="image-20201215000614183"></p>
<h3 id="5-4-小结"><a href="#5-4-小结" class="headerlink" title="5.4. 小结"></a>5.4. 小结</h3><p>Topic主题模式可以实现 <code>Publish/Subscribe发布与订阅模式</code> 和 <code> Routing路由模式</code> 的功能；只是Topic在配置routing key 的时候可以使用通配符，显得更加灵活。</p>
<h2 id="6-模式总结"><a href="#6-模式总结" class="headerlink" title="6. 模式总结"></a>6. 模式总结</h2><p>RabbitMQ工作模式：<br><code>1、简单模式 HelloWorld</code></p>
<p>一个生产者、一个消费者，不需要设置交换机（使用默认的交换机）</p>
<p>`2、工作队列模式 Work Queue</p>
<p>一个生产者、多个消费者（竞争关系），不需要设置交换机（使用默认的交换机）</p>
<p><code>3、发布订阅模式 Publish/subscribe</code></p>
<p>需要设置类型为fanout的交换机，并且交换机和队列进行绑定，当发送消息到交换机后，交换机会将消息发送到绑定的队列</p>
<p><code>4、路由模式 Routing</code></p>
<p>需要设置类型为direct的交换机，交换机和队列进行绑定，并且指定routing key，当发送消息到交换机后，交换机会根据routing key将消息发送到对应的队列</p>
<p><code>5、通配符模式 Topic</code></p>
<p>需要设置类型为topic的交换机，交换机和队列进行绑定，并且指定通配符方式的routing key，当发送消息到交换机后，交换机会根据routing key将消息发送到对应的队列</p>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/RabbitMQ/">RabbitMQ</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://s2.loli.net/2022/08/21/Ay5sujrkH1nLTwW.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://s2.loli.net/2022/08/21/Ay5sujrkH1nLTwW.jpg" alt="Wechat"/></a><div class="post-qr-code-desc">Wechat</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/73db57c3/"><img class="prev-cover" src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">原子操作的实现原理</div></div></a></div><div class="next-post pull-right"><a href="/posts/f5e26240/"><img class="next-cover" src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">什么是CAS?</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/66c89092/" title="消息队列RabbitMQ"><img class="cover" src= "" data-lazy-src="https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-07</div><div class="title">消息队列RabbitMQ</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/20/hk9Zvq4YRsIcnrw.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">樱桃先生</div><div class="author-info__description">樱桃先生的博客小站</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">78</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">65</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">21</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/typoraWechat.jpeg"><i class="fab fa-weixin"></i><span>加为好友</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎光临樱桃小窝🍒～评论系统日常崩溃，没有找到长期稳定好用的组件。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#RabbitMQ%E5%B7%A5%E4%BD%9C%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.</span> <span class="toc-text">RabbitMQ工作模式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Work-queues%E5%B7%A5%E4%BD%9C%E9%98%9F%E5%88%97%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.1.</span> <span class="toc-text">1. Work queues工作队列模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">1.1.1.</span> <span class="toc-text">1.1 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">1.1.2.</span> <span class="toc-text">1.2 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85"><span class="toc-number">1.1.2.1.</span> <span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851"><span class="toc-number">1.1.2.2.</span> <span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852"><span class="toc-number">1.1.2.3.</span> <span class="toc-text">消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">1.1.3.</span> <span class="toc-text">1.3 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">1.1.4.</span> <span class="toc-text">1.4 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.2.</span> <span class="toc-text">2. 订阅模式类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Publish-Subscribe%E5%8F%91%E5%B8%83%E4%B8%8E%E8%AE%A2%E9%98%85%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.3.</span> <span class="toc-text">3. Publish&#x2F;Subscribe发布与订阅模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">1.3.1.</span> <span class="toc-text">3.1 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">1.3.2.</span> <span class="toc-text">3.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-1"><span class="toc-number">1.3.2.1.</span> <span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851-1"><span class="toc-number">1.3.2.2.</span> <span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852-1"><span class="toc-number">1.3.2.3.</span> <span class="toc-text">消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">1.3.3.</span> <span class="toc-text">3.3 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">1.3.4.</span> <span class="toc-text">3.4 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Routing%E8%B7%AF%E7%94%B1%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.4.</span> <span class="toc-text">4. Routing路由模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">1.4.1.</span> <span class="toc-text">4.1 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">1.4.2.</span> <span class="toc-text">4.2 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-2"><span class="toc-number">1.4.2.1.</span> <span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851-2"><span class="toc-number">1.4.2.2.</span> <span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852-2"><span class="toc-number">1.4.2.3.</span> <span class="toc-text">消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">1.4.3.</span> <span class="toc-text">4.3 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">1.4.4.</span> <span class="toc-text">4.4 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-Topics%E9%80%9A%E9%85%8D%E7%AC%A6%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.5.</span> <span class="toc-text">5. Topics通配符模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-%E6%A8%A1%E5%BC%8F%E8%AF%B4%E6%98%8E"><span class="toc-number">1.5.1.</span> <span class="toc-text">5.1. 模式说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-%E4%BB%A3%E7%A0%81"><span class="toc-number">1.5.2.</span> <span class="toc-text">5.2. 代码</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-3"><span class="toc-number">1.5.2.1.</span> <span class="toc-text">生产者</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%851-3"><span class="toc-number">1.5.2.2.</span> <span class="toc-text">消费者1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E8%80%852-3"><span class="toc-number">1.5.2.3.</span> <span class="toc-text">消费者2</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-%E6%B5%8B%E8%AF%95"><span class="toc-number">1.5.3.</span> <span class="toc-text">5.3 测试</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-4-%E5%B0%8F%E7%BB%93"><span class="toc-number">1.5.4.</span> <span class="toc-text">5.4. 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E6%A8%A1%E5%BC%8F%E6%80%BB%E7%BB%93"><span class="toc-number">1.6.</span> <span class="toc-text">6. 模式总结</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/4995/" title="顺德好友小聚"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="顺德好友小聚"/></a><div class="content"><a class="title" href="/posts/4995/" title="顺德好友小聚">顺德好友小聚</a><time datetime="2023-05-07T13:41:30.660Z" title="更新于 2023-05-07 21:41:30">2023-05-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/51438/" title="旅游归来的周末"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="旅游归来的周末"/></a><div class="content"><a class="title" href="/posts/51438/" title="旅游归来的周末">旅游归来的周末</a><time datetime="2023-05-06T06:06:54.933Z" title="更新于 2023-05-06 14:06:54">2023-05-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/34851/" title="与好友的广西之旅"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="与好友的广西之旅"/></a><div class="content"><a class="title" href="/posts/34851/" title="与好友的广西之旅">与好友的广西之旅</a><time datetime="2023-05-02T08:08:36.497Z" title="更新于 2023-05-02 16:08:36">2023-05-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/36794/" title="信用卡业务汇总"><img src= "" data-lazy-src="https://s2.loli.net/2022/08/22/kpfRHFaCWDTNAu1.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="信用卡业务汇总"/></a><div class="content"><a class="title" href="/posts/36794/" title="信用卡业务汇总">信用卡业务汇总</a><time datetime="2023-05-02T06:30:21.691Z" title="更新于 2023-05-02 14:30:21">2023-05-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/53652/" title="项目管理笔记"><img src= "" data-lazy-src="https://ytblogpic.oss-cn-guangzhou.aliyuncs.com/blog-common.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="项目管理笔记"/></a><div class="content"><a class="title" href="/posts/53652/" title="项目管理笔记">项目管理笔记</a><time datetime="2023-05-02T06:29:26.948Z" title="更新于 2023-05-02 14:29:26">2023-05-02</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/xyingtao/blogimage/raw/master/img/RabbitMQ.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 樱桃先生</div><div class="footer_custom_text">一切都是最好的安排</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'https://twikoo-seven-fawn.vercel.app',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo-seven-fawn.vercel.app',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script>window.addEventListener('load', () => {
  const changeContent = (content) => {
    if (content === '') return content

    content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]') // replace image link
    content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]') // replace url
    content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]') // replace code
    content = content.replace(/<[^>]+>/g,"") // remove html tag

    if (content.length > 150) {
      content = content.substring(0,150) + '...'
    }
    return content
  }

  const getComment = () => {
    const runTwikoo = () => {
      twikoo.getRecentComments({
        envId: 'https://twikoo-seven-fawn.vercel.app',
        region: '',
        pageSize: 6,
        includeReply: true
      }).then(function (res) {
        const twikooArray = res.map(e => {
          return {
            'content': changeContent(e.comment),
            'avatar': e.avatar,
            'nick': e.nick,
            'url': e.url + '#' + e.id,
            'date': new Date(e.created).toISOString()
          }
        })

        saveToLocal.set('twikoo-newest-comments', JSON.stringify(twikooArray), 10/(60*24))
        generateHtml(twikooArray)
      }).catch(function (err) {
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom.innerHTML= "无法获取评论，请确认相关配置是否正确"
      })
    }

    if (typeof twikoo === 'object') {
      runTwikoo()
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(runTwikoo)
    }
  }

  const generateHtml = array => {
    let result = ''

    if (array.length) {
      for (let i = 0; i < array.length; i++) {
        result += '<div class=\'aside-list-item\'>'

        if (true) {
          const name = 'data-lazy-src'
          result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
        }
        
        result += `<div class='content'>
        <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
        <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
        </div></div>`
      }
    } else {
      result += '没有评论'
    }

    let $dom = document.querySelector('#card-newest-comments .aside-list')
    $dom.innerHTML= result
    window.lazyLoadInstance && window.lazyLoadInstance.update()
    window.pjax && window.pjax.refresh($dom)
  }

  const newestCommentInit = () => {
    if (document.querySelector('#card-newest-comments .aside-list')) {
      const data = saveToLocal.get('twikoo-newest-comments')
      if (data) {
        generateHtml(JSON.parse(data))
      } else {
        getComment()
      }
    }
  }

  newestCommentInit()
  document.addEventListener('pjax:complete', newestCommentInit)
})</script><script src="/js/jquery.min.js"></script><div class="aplayer no-destroy" data-id="5225697049" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="false" data-mini="true" data-lrctype="-1"> </div><script src="https://cdn.jsdelivr.net/gh/xiabo2/CDN@latest/fishes.js"></script><link rel="stylesheet" href="/css/utils.css"><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":170,"height":280},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>